﻿using System;
using System.Collections.Concurrent;
using Newtonsoft.Json;

namespace Inovout.Serializer
{
    public static class JsonNetSerializer
    {

        public static string Serialize(object data, Type containerType = null)
        {
            containerType = containerType ?? data.GetType();
            return Serialize(data, CreateJsonSerializerSettings(containerType));
        }
        public static string Serialize(object data, JsonSerializerSettings jsonSerializerSettings)
        {
            jsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            return JsonConvert.SerializeObject(data, jsonSerializerSettings);
        }
        private static readonly ConcurrentDictionary<Type, JsonSerializerSettings> JsonSerializerSettingsCache = new ConcurrentDictionary<Type, JsonSerializerSettings>();
        private static JsonSerializerSettings CreateJsonSerializerSettings(Type type)
        {

            return
                 JsonSerializerSettingsCache.GetOrAdd(type, (t) =>
                 {
                     JsonSerializerSettings settings = new JsonSerializerSettings();
                     settings.ContractResolver = new InterfaceContractResolver(type);
                     return settings;
                 });
        }

    }
}
